<template>
  <div class="change-password-container">
    <el-form ref="passwordForm" :model="passwordForm" label-width="120px">
      <el-form-item label="原密码">
        <el-input
          :type="showPassword ? 'text' : 'password'"
          v-model="passwordForm.oldPassword"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input
          :type="showPassword ? 'text' : 'password'"
          v-model="passwordForm.newPassword"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码">
        <el-input
          :type="showPassword ? 'text' : 'password'"
          v-model="passwordForm.confirmNewPassword"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="text"
          @click="showPassword = !showPassword"
        >{{ showPassword ? '隐藏密码' : '显示密码' }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">修改密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      userId: '',
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmNewPassword: "",
      },
      showPassword: false
    };
  },
  methods: {
    submitForm() {
    // 首先可以在这执行前端验证，比如新密码和确认新密码是否一致
    if (
      this.passwordForm.newPassword !== this.passwordForm.confirmNewPassword
    ) {
      // 如果密码不一致，可以显示一个错误消息并终止提交
      alert("新密码和确认新密码不匹配，请重新输入。");
      return; // 终止方法执行，防止发送请求
    }
    this.isSubmitting = true; // 标记为正在提交

    // 组装请求数据
    const requestData = {
      oldPassword: this.passwordForm.oldPassword,
      newPassword: this.passwordForm.newPassword,
      userId: this.userId
      // 如果需要，还可以包含其他信息，例如用户ID
    };

    // 使用axios发送请求
    this.$axios
      .post("api/employee/changePassword", requestData)
      .then(res => {
        if (res.data.code == 200) {
          console.log("密码更改成功", res);
          this.$message({
            message: "密码修改成功",
            type: "success"
          });
        
            this.$router.push({ path: "/login" });
        
        }
    
      })
      .catch(error => {
        // 在捕获错误的情况下，显示错误消息
        this.$message.error("密码修改失败，请重试。");
        console.error("密码修改失败", error);
      })
      .finally(() => {
        this.isSubmitting = false; // 标记为提交完成
      });
  }
},
  
  created() {
    this.userId = window.localStorage.getItem('userId');
  }
};
</script>
  
  <style scoped>
.change-password-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>